package com.carful.xigua.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.carful.xigua.modules.user.entity.Auth;
import com.carful.xigua.modules.user.entity.Role;
import com.carful.xigua.modules.user.entity.RoleAuth;
import com.carful.xigua.modules.user.mapper.RoleMapper;
import com.carful.xigua.modules.user.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ad
 * @since 2024-07-11
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleAuthServiceImpl roleAuthService;

    @Autowired
    private AuthServiceImpl authService;

    @Override
    public void init() {
        // 检查数据库中是否存在角色
        Role admin = getOne(new LambdaQueryWrapper<Role>().eq(Role::getValue, "admin"));
        if (admin == null) {
            admin = new Role();
            admin.setValue("admin").setName("超级管理员").setNotes("所有权限");
            save(admin);
        }
        Auth auth = authService.getOne(new LambdaQueryWrapper<Auth>().eq(Auth::getValue, "/"));
        RoleAuth roleAuth = new RoleAuth().setRoleId(admin.getId()).setAuthId(auth.getId());
        if (roleAuthService.getOne(new LambdaQueryWrapper<>(roleAuth)) == null) {
            boolean insert = roleAuthService.save(roleAuth);
            if (!insert) {
                log.error("超级管理员角色初始权限失败");
            }
        }
    }
}
